package cn.dlc.com.user.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author 邓立川
 * @date 2021/11/21 10:15
 * @desc 当前类的描述信息
 */
@Controller
// 后面这个用来设置编码的
@RequestMapping(value = "user",produces = {"text/plain;charset=UTF-8"})
public class UserController {


    @PostMapping("/login-success")
    public String authentication() {

        System.out.println("进入自己定义的登录成功方法，跳转到index");

        return "index";
    }

    // 注意，这个不能指定是get或者post，会有问题，不知道为啥
    @RequestMapping("/logout-success")
    public String logoutSuccess() {

        System.out.println("进入自己的logut-success，跳转到login");

        return "login";
    }




//    @PreAuthorize("hasAnyAuthority('p1')")
    @GetMapping(value="r/r1",produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public String resource1(HttpSession session){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if(principal != null && principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            return userDetails.getUsername() + "访问资源1";
        }

        return "资源1";
    }

    // @PreAuthorize("hasPermission('r/r2','p2')")
    @GetMapping(value= "r/r2",produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public String resource2(HttpSession session){

        return "资源2";
    }
}
